import pyautogui
import requests
import keyboard
import io
import time
from config import Config



def screenshot_and_recognize():
    print("开始截图识别...")
    image = pyautogui.screenshot()
    buffer = io.BytesIO()
    image.save(buffer, format='PNG')
    buffer.seek(0)

    try:
        print("发送请求到服务端...")
        response = requests.post(
            Config.API_ENDPOINT,
            files={'image': ('screenshot.png', buffer, 'image/png')}
        )
        response.raise_for_status()
        result = response.json().get('text', [''])

        # 先释放所有可能被按住的键
        pyautogui.keyUp('shift')
        pyautogui.keyUp('ctrl')
        pyautogui.keyUp('alt')

        # 添加短暂延迟确保键盘状态正常
        time.sleep(0.2)

        # 逐字符输入，字母按Shift，数字和符号不按Shift
        for char in result:
            if char.isalpha():  # 如果是字母
                pyautogui.keyDown('shift')
                pyautogui.press(char.lower())  # 确保传入小写字母
                pyautogui.keyUp('shift')
            else:  # 数字或符号
                pyautogui.press(char)
            time.sleep(0.05)  # 小延迟确保输入稳定

        time.sleep(0.1)
        pyautogui.press('enter')

    except Exception as e:
        print("识别失败：", e)


# 设置热键
keyboard.add_hotkey('ctrl+m', screenshot_and_recognize)
print("热键客户端已启动，按 ctrl+m 截图并识别，按 ESC 退出")
keyboard.wait('esc')